package com.ycfmedical.bed.utils;

import com.ycfmedical.bed.listener.RefreshCallBack;

import java.util.ArrayList;

import cn.droidlover.xdroidmvp.log.XLog;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/3/15.
 * 接收数据工具类
 */

public class RefreshDataUtils {
    private ArrayList<RefreshCallBack> refreshCallBacks;
    private static RefreshDataUtils refreshDataUtils = new RefreshDataUtils();

    private RefreshDataUtils() {
        refreshCallBacks = new ArrayList<RefreshCallBack>();
    }

    public static RefreshDataUtils getRefreshDataUtils() {
        return refreshDataUtils;
    }

    //在线程中调用的传递数据方法
    public void setData(int flag,String data) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext(data);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.immediate())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                        //先判断再解除绑定
                        if (isUnsubscribed()) {
                            unsubscribe();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        for (int i = 0; i < refreshCallBacks.size(); i++) {
                            refreshCallBacks.get(i).setData(flag, data);
                        }
                    }
                });
    }
    public void register(RefreshCallBack refreshCallBack) {
        refreshCallBacks.add(refreshCallBack);
    }

    public void remove(RefreshCallBack refreshCallBack) {
        refreshCallBacks.remove(refreshCallBack);
    }

}
